<?php

# 
# Copyright (c) 2002-2007 Eric Wallengren
# This file is part of the Continuous Automated Build and Integration 
# Environment (CABIE)
# 
# CABIE is distributed under the terms of the GNU General Public
# License version 2 or any later version.  See the file COPYING for copying 
# permission or http://www.gnu.org. 
#                                                                            
# THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED OR  
# IMPLIED, without even the implied warranty of MERCHANTABILITY or FITNESS 
# FOR A PARTICULAR PURPOSE.  ANY USE IS AT YOUR OWN RISK. 
#                                                                            
# Permission to modify the code and to distribute modified code is granted, 
# provided the above notices are retained, and a notice that the code was 
# modified is included with the above copyright notice. 
# 

    require_once('auth.php');

    print "<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en'>\n".
          "<head>\n".
          "<title>cabie dashboard</title>\n".
          "<link rel='stylesheet' href='/cabie.css' type='text/css'>\n";

    $val = $_POST{'submit'};
    $ref = $_POST{'referer'};

    switch ($val) { 
        case 'Cancel':
            echo "<meta http-equiv=\"REFRESH\" content=\"0;url=$ref\">";
            break;
        case 'Submit':
            echo "<meta http-equiv=\"REFRESH\" content=\"0;url=$ref\">";
            break;
    }

?>

</head>
<body>
<script type="text/javascript" src="javascript/wz_tooltip.js"></script>
<script type="text/javascript" src="javascript/gen_validatorv2.js"></script>

<?php 

    require_once("dbdefs.php");
    require_once('xmlrpc.inc');
   
    $SQL = new sqlfuncs();

    $buildserver = $_REQUEST['server'];
    $name        = $_REQUEST['name'];
    $number      = $_REQUEST['jobno'];
    $action      = $_REQUEST['action'];
    $table       = $_REQUEST['table'];
    $testname    = $_REQUEST['testname'];

    $buildstates = array('untested', 'failed test', 'failed build', 
                         'passed test', '', '', '', '', 'failed unit');

    $SQL->__construct($server, $username, $password, $database);
    
    $sqlarray = _getactiveservers($SQL, 1);

    $referer = $_SERVER["HTTP_REFERER"];

    _displayactiveservers($sqlarray, $buildserver);

    if ($menus[$table]['server']) {
        _servermenu($SQL, $buildserver);
    }

    $user = $_SESSION['PHP_AUTH_USER'];

    $userlevel  = $access[$table]['userlevel'];
    $adminlevel = $access[$table]['adminlevel'];

    if (!isset($user)) {
        $user = 'unknown';
    }
    $ok = _verifylevel($SQL, $user, $userlevel);

    if ($_REQUEST['user']) {
        if ($menus[$table]['job']) {
            $class = _getrunningclass($SQL, $_REQUEST['server'], 
                                      $_REQUEST['name']);
            if (isset($_REQUEST['name'])) {
                _jobmenu($SQL, $_REQUEST['server'], $_REQUEST['name'] ,
                         $class, 8);
            }
        }
    }

    if (!$ok) {
        errormessage("access to edit $table table denied", 8);

        echo "</tbody>\n".
             "</table>\n".
             "</div>\n";
        $mem = memory_get_usage();
        $usage = sprintf("%d", $mem/1024);
        echo "<p>memory used: ".$usage."k</p>\n";
        echo "</body>\n".
             "</html>\n";

        exit;
    }

    switch ($action) {

        case 'view':

            break;

        case 'edit':

            $editstring="/editor.php?server=$buildserver&action=edit".
                        "&table=$table&user=1&access=login";

            echo "<tr>\n".
                 "    <td class=\"jobname\" colspan=2>\n".
                 "\t<img src=/cabieicons/table_edit.png alt=\"edit\">".
                 "\t<a href=$editstring><img src=/cabieicons/table_add.png ".
                 "onmouseover=\"Tip('add new record')\" alt=\"edit\"></a>".
                 "\t<img src=/cabieicons/table_delete.png alt=\"edit\">".
                 "&nbsp;$table editor".
                 "    </td>\n".
                 "</tr>\n";

            $format    = $queries[$table]{search};
            $newformat = $queries[$table]{newsearch};

            switch ($table) {
                
                case 'configuration':
                    if (isset($name)) {
                        $query = sprintf("$format", $table, $buildserver, 
                                          $name);
                        $sqlarray = $SQL->sql_query($query, "+");
                    }
                    break;
                
                case 'testconfiguration':
                    $query = sprintf("$format", $table, "$buildserver:$name",
                                     $testname);
                    $sqlarray = $SQL->sql_query($query, "+");
                    break;
                
                case 'users':
                    $loggedlevel = _returnlevel($SQL, $user);
                    if ($loggedlevel < $adminlevel) {
                        $query = sprintf("$format", $table, $user);
                    } else {
                        $query = sprintf("$format", $table, $name);
                    }
                    $sqlarray = $SQL->sql_query($query, "+");
                    break;
             
                case 'comments':
                    $now   = $SQL->_get_hosttime();
                    $date  = date('m/d/Y h:i:s A', $now);
                    $query = sprintf("$format", $table, $buildserver, $name,
                                     $number);
                    $sqlarray = $SQL->sql_query($query, "+");
                    if (count($sqlarray) == 0) {
                        $query = sprintf("$newformat",  $buildserver, $name,
                                     $number);
                        $newsqlarray = $SQL->sql_query($query, "+");
                        $bstatus     = $newsqlarray[0];
                        $sqlarray[0] = "$buildserver+$name+$number++<$user> ".
                                       "$date:++".
                                       $buildstates[$bstatus];
                    } else {
                        list($bserver, $bname, $bnum, $bcomm, $bstatus) =
                            split('\+', $sqlarray[0], 5);
                        $sqlarray[0] = "$bserver+$bname+$bnum+$bcomm+<$user> ".
                                       "$date:++".
                                       $buildstates[$bstatus];
                    }
                    break;

            }

            _genForm($SQL, $tables[$table], $table, $sqlarray[0], $buildserver, 
                     $name, $number, $referer); 
            break;

        default:

            $c = 0;

            $combined;
            $bcombine  = 0;
            $cnoop     = 0;
            $snoop     = 0;

            $ttype     = $tables[$table]{type};
            $buttonval = $_POST{'submit'};
            
            if (( 0 == strcmp($buttonval, "Submit"))) {

                foreach ($_POST as $key => $value) {

                    $ttype   = $tables[$table]{$key}{'type'};
                    $combine = $tables[$table]{$key}{'combine'};

                    if(isset($combine)) {

                        $bcombine = 1;

                        if (!isset($combined)) {
                            if (!strlen(trim($value))) {
                                $first = 1;
                                $value = $_POST{$combine};
                            } else {
                                $value .= '\n'.trim($_POST{$combine}).'\n';
                            }
                            $combined .= $value.'\n';
                        } else {
                            if ($first) {
                                $combined .= '\n'.trim($_POST{$combine});
                            } else {
                                $combined .= trim($_POST{$combine});
                            }
                        }

                    } else {
                        $bcombine = 0;
                    }

                    switch ($key) {

                        case 'user':
                            $replace = ltrim($value);

                        case 'submit':
                            break;
                  
                        case 'referer':
                            break;

                        case 'v_verification':
                            break;
                  
                        case 'temp':
                            $oldvalues = explode('+', $value);
                            array_pop($oldvalues);
                            break;
                  
                        case 'table':
                            break;

                        case 'newcomment':
                            if (strlen(trim($value)) == 0) {
                                $cnoop = 1;
                            }
                        
                        default:

                            if ($bcombine) {
                                break;
                            }

                            $zero = $tables[$table]{$key}{'bool'}{'0'};
                            $one  = $tables[$table]{$key}{'bool'}{'1'};

                            $len  = strlen($one);
        
                            if ($len) {

                                if (_isEqual($zero, "yes")) {
                                    $vals = array("yes" => 0, "no" => 1);
                                }
        
                                if (_isEqual($zero, "no")) {
                                    $vals = array("yes" => 1, "no" => 0);
                                }
        
                                $setto = $vals{"$value"};
                                $values[$c] = utrim($setto);
        
                            } else {
                                $values[$c] = utrim($value);
                            }
        
                            $c++;

                            break;

                   }

                }

                $server   = $_POST['server'];
                $title    = $_POST['title'];
                $number   = $_POST['job'];
                $username = $_POST['username'];

                $cformat = $queries[$table]{condition};
                $sformat = $queries[$table]{search};

                switch ($table) {
                 
                    case 'configuration':
                        $query = sprintf("$sformat", $table, $server, $title);
                        $condition = sprintf("$cformat", $server, $title);
                        break;
                 
                    case 'testconfiguration':
                        $buildjob = $_POST['buildjob'];
                        $query = sprintf("$sformat", $table, $buildjob, $title,
                                         $testname);
                        $condition = sprintf("$cformat", $buildjob, $title);
                        break;
                 
                    case 'users':
                        $query = sprintf("$sformat", $table, $username);
                        $condition = sprintf("$cformat", $username);
                        break;

                    case 'comments':
                        $sformat = $queries[$table]{subsearch};
                        $query = sprintf("$sformat", $table, $server, $title, 
                                         $number);
                        $condition = sprintf("$cformat", $server, $title,
                                             $number);
                        $values[3] = $combined;
                        $nstatus   = array_pop($values);

                        switch($nstatus) {
                            case 'untested':
                                $nstatus = 0;
                                break;
                        
                            case 'failed test':
                                $nstatus = 1;
                                break;

                            case 'passed test':
                                $nstatus = 3;
                                break;

                            case 'failed unit':
                                $nstatus = 8;
                                break;

                        }

                        $ostatus   = array_pop($oldvalues);

                        if (strcmp($buildstates[$nstatus], $ostatus) == 0) {
                            $snoop = 1;
                            $statestring = '';
                        } else {
                            $stat = $queries[$table]{statup};
                            $submit = sprintf("$stat", $nstatus, $server, 
                                              $title, $number);
                            $sqlarray = $SQL->sql_update($submit);
                            $statestring = "state change: ".
                                           $buildstates[$nstatus];
                        }

                        #
                        # Since pop doesn't seem to be working do this 
                        # without calling pop (arrgh!)
                        #
                        if(isset($oldvalues[5])) {
                            unset($oldvalues[5]);
                        }
                        if(isset($oldvalues[4])) {
                            unset($oldvalues[4]);
                        }

                        #
                        # Don't submit an unchanged record
                        #
                        if ($cnoop == 1 && $snoop == 1) {
                            exit;
                        } else {

                            if ($cnoop == 1 && $snoop == 0) {
                                $values[3] .= $statestring;
                            }
                            if ($cnoop == 0 && $snoop == 0) {
                                $values[3] .= "\n\n".$statestring;
                            }
                       
                        }

                        break;

                }

                $sqlarray = $SQL->sql_query($query, ";");

                $numrecs = sizeof($sqlarray);

                if ($numrecs > 0) {

                    $updatequery = _updatequery($SQL, $tables[$table], $table, 
                                                $oldvalues, $values, 
                                                $condition);

                    if(strlen($updatequery) != 0) {
                        $sqlarray = $SQL->sql_update($updatequery);
                    }
    
                } else {

                    $ret = $SQL->sql_submit("$table", $values, $tables[$table]);

                }

            }
    
    }

    echo "</tbody>\n".
         "</table>\n".
         "</div>\n";

?>

</div>

<?php
    $mem = memory_get_usage();
    $usage = sprintf("%d", $mem/1024);
    echo "<p>memory used: ".$usage."k</p>\n";
?>

</body>
</html>

<?php
    exit;
?>
